package dados;


import java.util.ArrayList;
import java.io.*;
import negocios.cinemaBeans.Exibicao;



public class RepositorioExibicao implements Serializable {
	private ArrayList<Exibicao> arrayExibicao = new ArrayList<Exibicao>();


	private static RepositorioExibicao instance;

	
	public static RepositorioExibicao getInstance(){
		instance = recuperaArquivoExibicao();
		
		if (instance == null){
				instance = new RepositorioExibicao();
		}
		return instance;
	}
	
	
	
	private RepositorioExibicao(){
		
	}



	public void adicionaExibicao(Exibicao exibicao) throws  IOException{
		if(exibicao.getFilme()!=null && exibicao.getHorario()!=null){
			if(!this.verificaExibicao(exibicao)){
				this.arrayExibicao.add(exibicao);
				gravaArquivoExibicao();	
			}
			
		}else{
			IOException io = new IOException();
			throw io;
		}

	}


	public ArrayList<Exibicao> listaExibicao(){
		return this.arrayExibicao;
	}


	public void removeExibicao(Exibicao exibicao){
		this.arrayExibicao.remove(exibicao);
	}

	
	protected static void gravaArquivoExibicao() throws IOException{
		if (instance == null){
			return;
		}
		File f = new File("exibicao.dat");
		
		if (!f.exists()){
			f.createNewFile();
		}
		
		FileOutputStream faos = new FileOutputStream(f);
		ObjectOutputStream w = new ObjectOutputStream(faos);
		w.writeObject(instance);
		w.close();
		
	}
	
	protected static RepositorioExibicao recuperaArquivoExibicao() {
		RepositorioExibicao clone = null;
		
		try{
			File f = new File("exibicao.dat");
			FileInputStream fis = new FileInputStream(f);
			ObjectInputStream ois = new ObjectInputStream(fis);
			Object rep = ois.readObject();
			clone = (RepositorioExibicao)rep;
			ois.close();	
		} catch (FileNotFoundException e) {
			return clone;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return clone;
	}
	
	protected boolean verificaExibicao(Exibicao exibicao){
		for(Exibicao buscaExibicao : this.arrayExibicao){
			if(exibicao.getFilme().equals(buscaExibicao.getFilme()) 
					&& exibicao.getHorario().equals(buscaExibicao.getHorario())){
				return true;
			}
		}
		return false;
	}
}
